package com.frame.exception.handle;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.frame.stant.constans.ResultCode;
import com.frame.exception.CustomAuthenticationException;

import com.frame.stant.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@ControllerAdvice
@Slf4j
public class ExceptionHandle {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        if("不允许访问".equals(e.getMessage())){
            return accessDeniedExceptionError(e);
        }
        e.printStackTrace();
        return R.error(StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : "系统异常");
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    @ResponseBody
    public R error(UsernameNotFoundException e) {
        e.printStackTrace();
        return R.error(StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : "用户不存在");
    }

    @ExceptionHandler(CustomAuthenticationException.class)
    @ResponseBody
    public R error(CustomAuthenticationException e) {
        e.printStackTrace();
        return R.error(StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : "认证失败");
    }

    /**
     * 没有资源访问权限
     * @param e
     * @return
     */
    private R accessDeniedExceptionError(Exception e){
        e.printStackTrace();
        return R.error(String.valueOf(ResultCode.USER_ACCESS_UNAUTHORIZED));
    }







}
